package com.geek.factory.security;

import cn.hutool.json.JSONUtil;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.result.Result;
import com.geek.factory.utils.WebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chenmin
 * @desc 针对于 401认证失败  403授权失败
 * @date 2025/7/7
 */
@Configuration
public class SecurityHandler {

    // 401认证失败
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint(){
        return new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                Result result = new Result(SuccessConstant.FAIL , authException.getMessage() , "401认证失败");
                WebUtils.renderString(response , JSONUtil.toJsonStr(result));
            }
        };
    }

    // 403授权失败
    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        return new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                Result result = new Result(SuccessConstant.FAIL ,accessDeniedException.getMessage(), "403授权失败");
                WebUtils.renderString(response , JSONUtil.toJsonStr(result));
            }
        };
    }

}
